home *** CD-ROM | disk | FTP | other *** search
/ PsL Monthly 1994 December / PSL Monthly Shareware CD-ROM (Public Software Library)(December 1994).bin / prgmming / dos / pascal2 / bresn.pas < prev    next >
Pascal/Delphi Source File  |  1993-01-05  |  2KB  |  62 lines

  1. // bresn.pas
  2. // file which shows how to draw a line
  3.  
  4. program bresn;
  5.  
  6. uses Graph;
  7.  
  8. procedure initialize;
  9. // initialize graphics
  10. var Gm, Gd : integer;
  11. begin
  12.    Gd := DETECT;
  13.    initgraph( gd, gm, '' );
  14. end;
  15.  
  16. procedure drawLine( xStart, yStart, xEnd, yEnd : integer );
  17. // draws line
  18. var dx, dy, E, NE, d, x, y : integer;
  19. begin
  20.    dx := xEnd-xStart;
  21.    dy := yEnd-yStart;
  22.    d := 2*dy-dx;
  23.    E := 2*dy;
  24.    NE := 2*(dy-dx);
  25.    x := xStart;
  26.    y := yStart;
  27.    putpixel( x, y, WHITE );
  28.    while x < xEnd do
  29.       begin
  30.          if d <= 0 then
  31.             begin
  32.                d := d+E;
  33.                x := x+1;
  34.             end
  35.          else
  36.             begin
  37.                d := d+NE;
  38.                x := x+1;
  39.                y := y+1;
  40.             end;
  41.          putpixel( x, y, WHITE );
  42.       end;
  43. end;
  44.  
  45. // The way Bresenham's algorithm (also known as midpoint algorithm) works
  46. // basically plotting the line raster by raster rather than producing it
  47. // by brute force with a formula.  Obviously, its better than using the
  48. // formula since it allows for vertical lines and uses no multiplication
  49. // or division.  The algorithm in its entirety uses 4 line algorithms for
  50. // slopes of 0 to 1, 1 to infinity, 0 to -1, and -1 to -infinity.  The
  51. // algorithm above shows just works for slopes 0 to -1, since the other
  52. // three are easily obtained with a few simple modifications.
  53. // What the algorithm does, in this case, is that it draws a line from
  54. // xStart,yStart to xEnd,yEnd.  It then computes the distance of the midpoint
  55. // between the two pixels to the line itself, KEEPING THE SIGN.  If the sign
  56. // is positive, then the plotter goes down one line as well as over one pixel.
  57. // If negative, then the plotter remains at the same line.  The plotter then
  58. // goes to the next point and repeats the process.  Bresenham's is extremely
  59. // useful for anti-aliased lines.  If you want, e-mail me and I'll send
  60. // details on that as well.
  61.  
  62. // chetan deshpande